# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup  # 网页解析，获取数据
import re  # 正则表达式，进行文字匹配
import urllib.request, urllib.error  # 指定url，获取网页数据
import xlwt  # 进行excel操作
import sqlite3  # 进行SQLite3数据库的操作


def main():
    baseurl = "https://movie.douban.com/top250?start="
    # 1.爬取网页
    dataList = getData(baseurl)
    # savePath = ".\\豆瓣电影Top250.xls"
    dbPath = "movie250.db"
    # 3.保存数据
    # saveData(dataList, savePath)
    # print('数据保存在'+savePath)
    saveData2DB(dataList, dbPath)


# 链接
findLink = re.compile(r'<a href="(.*?)">')  # 创建正则表达式对象，表示规则（字符串的模式）
# 图片
findImgSrc = re.compile(r'<img.*src="(.*?)"', re.S)  # re.S让换行字符包含在字符串中
# 片名
findTitle = re.compile(r'<span class="title">(.*)</span>')
# 评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 评价人数
findJudge = re.compile(r'<span>(\d*)人评价</span>')
# 影片概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
# 相关内容
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)  # 忽视换行符


# 爬取网页
def getData(baseurl):
    dataList = []
    for i in range(0, 10):
        url = baseurl + str(i * 25)
        # 保存获取的网页源码
        html = askUrl(url)

        # 逐一解析数据
        soup = BeautifulSoup(html, "html.parser")
        for item in soup.find_all('div', class_='item'):  # 查找符合要求的字符串，形成列表
            # print(item)  # 测试：查看电影item全部信息
            data = []
            item = str(item)
            # 影片详情的链接
            link = re.findall(findLink, item)[0]  # re库用来通过正则表达式查找指定的字符串
            data.append(link)
            imgSrc = re.findall(findImgSrc, item)[0]
            data.append(imgSrc)
            titles = re.findall(findTitle, item)
            if len(titles) == 2:
                cTitle = titles[0]
                data.append(cTitle)
                fTitle = titles[1].replace("/", "")  # 去掉无关的符号
                data.append(fTitle)
            else:
                data.append(titles[0])
                data.append(' ')  # 外文名为空

            rating = re.findall(findRating, item)[0]
            data.append(rating)
            judgeNum = re.findall(findJudge, item)[0]
            data.append(judgeNum)
            inq = re.findall(findInq, item)
            if len(inq) != 0:
                inq = inq[0].replace("。", "")  # 去掉符号
                data.append(inq)
            else:
                data.append(' ')  # 为空
            bd = re.findall(findBd, item)[0]
            bd = re.sub('<br(\s+)?/>(\s+)', " ", bd)  # 去掉<br/>
            bd = re.sub('/', ' ', bd)  # 替换/
            data.append(bd.strip())  # 去掉前后的空格
            dataList.append(data)
    print(dataList)
    return dataList


# 获取一个指定url的网页内容
def askUrl(url):
    # "User-Agent"即用户代理：告诉服务器自己是是什么类型的机器、浏览器（本质上是告诉服务器，我们可以接收什么水平的代码）
    headers = {  # 模拟浏览器头部信息，向豆瓣服务器发送消息
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    }
    request = urllib.request.Request(url, headers=headers)
    html = ""
    try:
        response = urllib.request.urlopen(request)
        html = response.read().decode('utf-8')
        # print(html)
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
        print('time out!')
    return html


# 保存数据
def saveData(dataList, savePath):
    print('save....')
    book = xlwt.Workbook(encoding='utf-8', style_compression=0)  # style_compression表示是否压缩
    sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True)  # 允许单元格重写
    col = ("影视链接", "图片链接", "影片中文名", "影片外国名", "评分", "评价数", "概况", "相关信息")
    # 添加列名
    for i in range(0, 8):
        sheet.write(0, i, col[i])

    # 写入数据
    for i in range(0, 250):
        print("第%d条" % (i + 1))
        data = dataList[i]
        for j in range(0, 8):
            sheet.write(i + 1, j, data[j])
    # 保存数据
    book.save(savePath)


def saveData2DB(dataList, dbPath):
    init_db(dbPath)
    conn = sqlite3.connect(dbPath)
    cur = conn.cursor()

    for data in dataList:
        for index in range(len(data)):
            if index == 4 or index == 5:
                continue
            data[index] = '"' + data[index] + '"'
        sql = '''
                insert into movie250 (link,imgSrc,cname,fname,rating,judgeNum,inq,bd)
                values(%s)''' % ",".join(data)
        print(sql)
        cur.execute(sql)
        conn.commit()
    cur.close()
    conn.close()


def init_db(dbPath):
    sql = '''
        create table movie250(
            id integer primary key autoincrement,
            link text,
            imgSrc text,
            cname varchar,
            fname varchar,
            rating numeric,
            judgeNum numeric,
            inq text,
            bd text
        )
    '''
    conn = sqlite3.connect(dbPath)
    cursor = conn.cursor()
    cursor.execute(sql)
    conn.commit()
    conn.close()


if __name__ == '__main__':
    main()
    # init_db("movie250.db")
